package com.java_project.src.network;

import com.java_project.src.Product;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;

public class EStoreClient {
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 8888;
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine();
            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 5:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选项，请重新输入！");
            }
        }
    }

    private void showMenu() {
        System.out.println("\n 欢迎来到商城 ");
        System.out.println("1. 浏览所有商品");
        System.out.println("5. 退出");
        System.out.print("请输入您的选择: ");
    }

    private void browseProducts() {
        try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
             ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
            oos.writeObject("GET_ALL_PRODUCTS");
            oos.flush();
            List<Product> products = (List<Product>) ois.readObject();
            System.out.println("\n--- 商品列表 ---");
            if (products.isEmpty()) {
                System.out.println("商店里还没有商品。");
            } else {
                products.forEach(System.out::println);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("获取商品列表失败，请检查服务器是否运行。");
        }
    }

    public static void main(String[] args) {
        new EStoreClient().start();
    }
}